﻿using Microsoft.AspNetCore.Mvc;
using JESAI.Core.Util.Helpers;
using JESAI.Core.Util.IO;
using JESAI.Framework.Attributes;
using JESAI.Framework.Mvc;
using System.Net;
using System.Net.Http.Headers;

namespace JESAI.Platform.WebApi.Controllers
{
    /// <summary>
    /// 日志拉取
    /// </summary>
    [ApiController]
    [Route("api/v1/[controller]/[action]")]
    public class LogPullController : ApiControllerBase
    {
        private readonly ILogger<LogPullController> _logger;

        public LogPullController(ILogger<LogPullController> logger)
        {
            _logger= logger;
        }

        /// <summary>
        /// 拉去日志接口
        /// </summary>
        /// <param name="logDate">日志时间</param>
        /// <returns></returns>
        [HttpGet]
        [WebApiAuthorization]
        public IActionResult PullLogZipFile(DateTime? logDate=null)
        {
            var logDateStr = logDate.HasValue ? logDate.Value.ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy-MM-dd");
            var tempDirPath = AppDomain.CurrentDomain.BaseDirectory + "FileTemp";
            if (!Directory.Exists(tempDirPath))
            {
                Directory.CreateDirectory(tempDirPath);
            }
            Directory.Delete(tempDirPath, true);
            FileStream fileStream = null;
            var zipFilePath = tempDirPath + "\\" + logDateStr + ".zip";
            try
            {
              
                if (System.IO.File.Exists(zipFilePath))
                {
                    System.IO.File.Delete(zipFilePath);
                }
               
                var logDirPath = AppDomain.CurrentDomain.BaseDirectory + "log\\" + logDateStr;
                DirectoryHelper.Copy(logDirPath, tempDirPath + "\\" + logDateStr);
                Compression.Zip(tempDirPath + "\\" + logDateStr, zipFilePath);

                fileStream = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite, 4096, true);  //异步读取文件
                return File(fileStream, "application/octet-stream", logDateStr+".zip",true);
            }
            catch(Exception ex)
            {
                _logger.LogException(ex);
                return null;
            }
            finally
            {
                Directory.Delete(tempDirPath+"\\"+ logDateStr, true);
            }
        }
    }
}
